package com.yulang.security.mobile;

import com.yulang.security.controller.CustomController;
import com.yulang.security.exception.ValidateCodeException;
import com.yulang.security.handler.CustomAuthFailureHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class MobileValidateFilter extends OncePerRequestFilter {


    @Autowired
    private CustomAuthFailureHandler customAuthFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest,
                                    HttpServletResponse httpServletResponse,
                                    FilterChain filterChain) throws ServletException, IOException {
        if(httpServletRequest.getRequestURI().equalsIgnoreCase("/mobile/form")
                && httpServletRequest.getMethod().equalsIgnoreCase(HttpMethod.POST.name())) {
            try {
                String attribute = httpServletRequest.getSession().getAttribute(CustomController.MOBILE_SESSION_KEY).toString();
                String code = httpServletRequest.getParameter("code");
                if(!code.equalsIgnoreCase(attribute)) {
                    throw new ValidateCodeException("验证码错误");
                }
            }catch (AuthenticationException e){
                customAuthFailureHandler.onAuthenticationFailure(httpServletRequest,httpServletResponse,e);
                return;
            }
        }

        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }
}
